package com.raising.framework.service;

import com.raising.framework.dao.ICrudDao;
import com.raising.framework.entity.BaseEntity;
import com.raising.framework.interceptor.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 * @author gaoy
 */
@Transactional(rollbackFor = Exception.class)
public abstract class CrudService<D extends ICrudDao<T>, T extends BaseEntity<T>>
        extends BaseService {

    /**
     * 持久层对象
     */
    @Autowired
    protected D dao;

    /**
     * 获取单条数据
     * @author GaoYuan
     * @param id
     * @datetime 2017/12/6 上午9:37
     * @return
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public T get(String id) {
        return dao.get(id);
    }

    /**
     * 获取单条数据
     * @author GaoYuan
     * @param entity
     * @datetime 2017/12/6 上午9:37
     * @return
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public T get(T entity) {
        return dao.get(entity);
    }

    /**
     * 查询列表数据
     * @author GaoYuan
     * @param entity
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public List<T> getList(T entity) {
        return dao.getList(entity);
    }
    /**
     * 查询分页
     * @author GaoYuan
     * @param page
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public Page<T> getPage(Page<T> page){
        page.setResults(dao.getPage(page));
        return page;
    }

    /**
     * 保存数据（插入或更新）
     * @author GaoYuan
     * @param entity
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(T entity) {
        if (entity.getIsNewId()) {
            entity.preInsert(null);
            return dao.insert(entity);
        } else {
            entity.preUpdate(null);
            return dao.update(entity);
        }
    }
    /**
     * 插入
     * @author GaoYuan
     * @param entity
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(rollbackFor = Exception.class)
    public int insert(T entity){
        return dao.insert(entity);
    }
    /**
     * 更新
     * @author GaoYuan
     * @param entity
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(rollbackFor = Exception.class)
    public int update(T entity){
        return dao.update(entity);
    }

    /**
     * 删除数据
     * @author GaoYuan
     * @param entity
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(rollbackFor = Exception.class)
    public int delete(T entity) {
        return dao.delete(entity);
    }

    /**
     * 删除数据
     * @author GaoYuan
     * @param id 主键
     * @datetime 2017/12/6 上午9:37
     */
    @Transactional(rollbackFor = Exception.class)
    public int delete(String id) {
        return dao.delete(id);
    }

}
